package com.itasura.guava.FunctionalProgramming;

import com.google.common.base.Function;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.AbstractMap;

/**
 * 普通function可自定义实现
 *
 * @author sailor wang
 * @date 2018/10/19 上午11:20
 * @description
 */
@Slf4j
public class FunctionTest {

    @Test
    public void functionTest() {
        // 匿名类的方式来完成了仿函数的定义、初始化和赋值
        Function<Double, Double> sqrt = new Function<Double, Double>() {
            @Override
            public Double apply(Double aDouble) {
                return Math.sqrt(aDouble);
            }
        };
        log.info("匿名 function -> {}", sqrt.apply(4.0));

        log.info("显示声明 function -> {}", new SqrtFunction().apply(4.0));

        Function<AbstractMap.SimpleEntry<Double, Double>, Double> pow = new Function<AbstractMap.SimpleEntry<Double, Double>, Double>() {
            @Override
            public Double apply(AbstractMap.SimpleEntry<Double, Double> doubleDoubleSimpleEntry) {
                return Math.pow(doubleDoubleSimpleEntry.getKey(), doubleDoubleSimpleEntry.getValue());
            }
        };
        Double val = pow.apply(new AbstractMap.SimpleEntry(3.0, 2.0));

        log.info("val -> {}", val);

        Function<Double[], Double> sumFun = new Function<Double[], Double>() {
            @Override
            public Double apply(Double[] doubles) {
                Double result = 0.;
                for (Double d : doubles) {
                    result += d;
                }
                return result;
            }
        };
        Double sum = sumFun.apply(new Double[]{1., 2., 3., 4., 5., 6., 7., 8., 9., 10.});
        log.info("sum -> {}", sum);
    }
}